<?php
/**
 * 使用cookie代替session.
 * @author iorichina
 *
 */
class WebUser extends CWebUser {
	public function getState($key, $defaultValue = null) {
		$key = $this->getStateKeyPrefix () . $key;
		if (isset ( $_COOKIE [$key] )) {
			$value = $_COOKIE [$key];
		}
		
		return $value ? $value : $defaultValue;
	}
	public function setState($key, $value, $defaultValue = null) {
		$key = $this->getStateKeyPrefix () . $key;
		if ($value === $defaultValue) {
			setcookie ( $key, '', time () - 3600 );
			unset ( $_COOKIE [$key] );
		} else {
			$value = is_array ( $value ) ? json_encode ( $value ) : $value;
			$_COOKIE [$key] = $value;
			// setcookie ( $key, $value, 0, '/', '.sitestar.com' );
			setcookie ( $key, $value, time () + 7200, '/', '.sitestar.com' );
		}
	}
	public function hasState($key) {
		$key = $this->getStateKeyPrefix () . $key;
		return isset ( $_COOKIE [$key] );
	}
	public function clearStates() {
		$keys = array_keys ( $_COOKIE );
		$prefix = $this->getStateKeyPrefix ();
		$n = strlen ( $prefix );
		foreach ( $keys as $key ) {
			if (! strncmp ( $key, $prefix, $n )) {
				setcookie ( $key, '', time () - 3600 );
				unset ( $_COOKIE [$key] );
			}
		}
	}
	public function getFlashes($delete = true) {
		$flashes = array ();
		$prefix = $this->getStateKeyPrefix () . self::FLASH_KEY_PREFIX;
		$keys = array_keys ( $_COOKIE );
		$n = strlen ( $prefix );
		foreach ( $keys as $key ) {
			if (! strncmp ( $key, $prefix, $n )) {
				$flashes [substr ( $key, $n )] = $_COOKIE [$key];
				if ($delete) {
					setcookie ( $key, '', time () - 3600 );
					unset ( $_COOKIE [$key] );
				}
			}
		}
		if ($delete)
			$this->setState ( self::FLASH_COUNTERS, array () );
		return $flashes;
	}
}